package com.example.end.mydairy;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SimpleCursorAdapter;
import android.os.Bundle;

import com.end.DaoMaster;
import com.end.DaoMaster.DevOpenHelper;
import com.end.DaoSession;
import com.end.Note;
import com.end.NoteDao;

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static final int menu_item_insert=Menu.FIRST;
    private static final int menu_item_edit=Menu.FIRST+1;
    public static final String TAG = "Dao";
    private SearchView search;
    private Builder dialog;
    private ListView list;
    private Toolbar toolbar;
    private SimpleCursorAdapter adapter;
    private long firstPressedTime;
    private String State="Normal";
    private String Flag="normal";

    private SQLiteDatabase db;
    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private NoteDao noteDao;
    private Cursor cursor;
    private Cursor search_cursor;
    private Note note;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        list=(ListView)findViewById(R.id.list_view);
        toolbar=(Toolbar)findViewById(R.id.toolbar);

        initdao();
        initList();

        setSupportActionBar(toolbar);
        list.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                setAlertDialog();
                return true;
            }
        });
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(State.equals("Normal"))
                {
                    Intent intent=new Intent(MainActivity.this,Editor.class);
                    intent.setAction(Editor.EDIT_DIARY_ACTION);
                    Bundle bundle=new Bundle();
                    bundle.putLong("id",id);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    MainActivity.this.finish();
                    cursor.requery();
                }
                else if(State.equals("Sharing"))
                {
                    note=noteDao.loadByRowId(id);
                    share();
                }

            }
        });
    }
    private void initdao() {
       DevOpenHelper helper=new DaoMaster.DevOpenHelper(this,"notes-db",null);
        db=helper.getWritableDatabase();
        daoMaster=new DaoMaster(db);
        daoSession=daoMaster.newSession();
        noteDao=daoSession.getNoteDao();
    }
    private void initList() {

        String textColumn=NoteDao.Properties.Title.columnName;
        String dateColumn=NoteDao.Properties.Date.columnName;
        String orderBy = dateColumn + " COLLATE LOCALIZED DESC";
        cursor=db.query(noteDao.getTablename(),noteDao.getAllColumns(),null,null,null,
                null,orderBy);
        String[] from={textColumn,dateColumn};
        int[] to={android.R.id.text1,android.R.id.text2};
        SimpleCursorAdapter adapter=new SimpleCursorAdapter(this,R.layout.list_item,
                cursor,from,to);
        list.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
    private void addNote()
    {
        Intent intent=new Intent(this,Editor.class);
        intent.setAction(Editor.INSERT_DIARY_ACTION);
        intent.setData(getIntent().getData());
        startActivity(intent);
        MainActivity.this.finish();
        cursor.requery();
    }
    private void search_Text(String title)
    {
        String textColumn=NoteDao.Properties.Title.columnName;
        String dateColumn=NoteDao.Properties.Date.columnName;
        search_cursor=db.query(noteDao.getTablename(),noteDao.getAllColumns(),"TITLE LIKE ?",new String[]{"%"+title+"%"},null,null,
                null);
        String[] from={textColumn,dateColumn};
        int[] to={android.R.id.text1,android.R.id.text2};
        SimpleCursorAdapter search_adapter=new SimpleCursorAdapter(MainActivity.this,R.layout.list_item,
                search_cursor,from,to);
        list.setAdapter(search_adapter);
        search_adapter.notifyDataSetChanged();
    }

     public boolean onCreateOptionsMenu(Menu menu)
     {

         MenuInflater menuInflater=getMenuInflater();
         menuInflater.inflate(R.menu.toolbar,menu);
         final MenuItem searchItem = menu.findItem(R.id.search);
         search= (SearchView) MenuItemCompat.getActionView(searchItem);
         search.setQueryHint("search...");
         search.setSubmitButtonEnabled(true);
         //search.onActionViewExpanded();
         search.setIconified(true);
         int id = search.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
         TextView textView = (TextView) search.findViewById(id);
         textView.setTextColor(getResources().getColor(R.color.search_text));
         textView.setHintTextColor(getResources().getColor(R.color.colorPrimary));
         search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
             @Override
             public boolean onQueryTextSubmit(String query) {
                 search.onActionViewCollapsed();
                 search.clearFocus();
                 search_Text(query);
                 Flag="summit";
                 return false;
             }

             @Override
             public boolean onQueryTextChange(String newText) {
                 if (newText.equals("")){
                     list.setAdapter(adapter);
                 }
                 search_Text(newText);
                 return false;
             }
         });
         super.onCreateOptionsMenu(menu);
         return true;
     }
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.New:
                addNote();
                break;
            case R.id.search:
                search.requestFocus();
                break;
            case R.id.share1:
                State="Sharing";
                Toast.makeText(MainActivity.this,"点 击日记进行分享",Toast.LENGTH_LONG).show();
                break;
            default:
                Log.d(TAG,"Wrong?");
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    protected void onActivityResult(int requestCode,int resultCode,Intent intent)
    {
        cursor.requery();
        super.onActivityResult(requestCode,resultCode,intent);
    }


    private void setAlertDialog()
    {
        Builder dialog=new AlertDialog.Builder(MainActivity.this,R.style.Theme_AppCompat_Light_Dialog_Alert);
        dialog.setTitle("你确定要删除吗？");
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                long id=cursor.getLong(cursor.getColumnIndex(NoteDao.Properties.Id.columnName));
                noteDao.deleteByKey(id);
                cursor.requery();
                Toast.makeText(MainActivity.this,"删除成功！",Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.create();
        dialog.show();
    }
    public void onBackPressed() {
        if(Flag.equals("normal"))
        {
            if (System.currentTimeMillis() - firstPressedTime < 2000) {
                super.onBackPressed();
            } else {
                Toast.makeText(MainActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
                firstPressedTime = System.currentTimeMillis();
            }
        }
        else if(Flag.equals("summit"))
        {
            Intent intent=new Intent(this,MainActivity.class);
            startActivity(intent);
            finish();
        }

    }
    public void share()
    {
        State="Normal";
        Intent textIntent = new Intent(Intent.ACTION_SEND);
        textIntent.setType("text/plain");
        textIntent.putExtra(Intent.EXTRA_TEXT,"标题："+note.getTitle().toString()
                +"\n正文："+note.getContent().toString()+"\n\n时间："+note.getDate().toString());
        startActivity(Intent.createChooser(textIntent, "分享"));
    }
}
